<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryFormRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="试卷名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入试卷名称"
          clearable
          @input="handleInput"
        />
      </el-form-item>
      <el-form-item label="所属科目" prop="subjectCode">
        <el-tree-select
          v-model="queryParams.subjectCode"
          :data="subjectOptions"
          node-key="id"
          :props="{
            label: 'name',
            value: 'id',
            children: 'children',
            emitPath: false
          }"
          placeholder="选择所属科目"
          check-strictly
          filterable
          :filter-node-method="filterSubjectNode"
          clearable
          style="width: 220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
        <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          :icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:paper:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          :icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:paper:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          :icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:paper:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          :icon="Download"
          @click="handleExport"
          v-hasPermi="['system:paper:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          :icon="Upload"
          @click="handleImport"
          v-hasPermi="['system:paper:import']"
        >导入</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="paperList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="试卷名称" align="center" prop="name" />
      <el-table-column label="所属科目" align="center" prop="subjectName" />
      <el-table-column label="排序" align="center" prop="sort" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            type="text"
            :icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:paper:edit']"
          >修改</el-button>
          <el-button
            type="text"
            :icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:paper:remove']"
          >删除</el-button>
          <el-button
            type="text"
            :icon="Document"
            @click="handleQuestions(scope.row)"
            v-hasPermi="['system:paper:questions']"
          >题目管理</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改试卷名称对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="试卷名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入试卷名称" />
        </el-form-item>
        <el-form-item label="所属科目" prop="subjectCode">
          <el-tree-select
            v-model="form.subjectCode"
            :data="subjectOptions"
            node-key="id"
            :props="{
              label: 'name',
              value: 'id',
              children: 'children',
              emitPath: false
            }"
            placeholder="选择所属科目"
            check-strictly
            default-expand-all
            filterable
            :filter-node-method="filterSubjectNode"
            clearable
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number 
            v-model="form.sort" 
            :min="0" 
            :max="999" 
            controls-position="right" 
            placeholder="请输入排序号"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导入试卷对话框 -->
    <el-dialog :title="'试卷导入'" v-model="importOpen" width="500px" append-to-body>
      <el-form ref="importFormRef" :model="importForm" :rules="importRules" label-width="100px">
        <el-form-item label="网站名称" prop="siteName">
          <el-select v-model="importForm.siteName" placeholder="请选择网站" style="width: 100%">
            <el-option
              v-for="item in siteOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="导入URL" prop="url">
          <el-input v-model="importForm.url" placeholder="请输入导入URL地址" />
        </el-form-item>
        <el-form-item label="认证Token" prop="token">
          <el-input v-model="importForm.token" placeholder="请输入认证Token" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" :loading="importLoading" @click="submitImport">确 定</el-button>
          <el-button @click="cancelImport">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Edit, Delete, Download, Document, Upload } from '@element-plus/icons-vue'
import { listPaper, getPaper, delPaper, addPaper, updatePaper, importPaper } from "@/api/paper"
import { tree as subjectTree } from "@/api/system/subject"

// 路由实例
const router = useRouter()

// ref声明
const loading = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const showSearch = ref(true)
const total = ref(0)
const paperList = ref([])
const title = ref('')
const open = ref(false)
const queryFormRef = ref()
const formRef = ref()
const importOpen = ref(false)
const importFormRef = ref()
const subjectOptions = ref([])
const importLoading = ref(false)

// reactive声明
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: null,
  subjectCode: null
})

const form = reactive({
  id: null,
  name: null,
  subjectCode: null,
  sort: 0,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null
})

const rules = reactive({
  name: [
    { required: true, message: '试卷名称不能为空', trigger: 'blur' },
    { min: 2, max: 50, message: '试卷名称长度必须在 2 到 50 个字符之间', trigger: 'blur' }
  ],
  subjectCode: [
    { required: true, message: '所属科目不能为空', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '排序号不能为空', trigger: 'blur' }
  ]
})

const TOKEN_STORAGE_KEY = 'importTokenCache'
const SITE_NAME_STORAGE_KEY = 'importSiteNameCache'

const importForm = reactive({
  siteName: localStorage.getItem(SITE_NAME_STORAGE_KEY) || '',
  url: '',
  token: localStorage.getItem(TOKEN_STORAGE_KEY) || ''
})

const importRules = reactive({
  siteName: [
    { required: true, message: '请选择网站名称', trigger: 'change' }
  ],
  url: [
    { required: true, message: '请输入导入URL', trigger: 'blur' },
    { type: 'url', message: '请输入有效的URL地址', trigger: 'blur' }
  ],
  token: [
    { required: true, message: '请输入认证Token', trigger: 'blur' }
  ]
})

// 添加网站选项数据
const siteOptions = ref([
  { value: '0', label: '勤思好学' }
])

// 方法定义
const getList = () => {
  loading.value = true
  listPaper(queryParams).then(response => {
    paperList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// ... 其他方法转换为组合式API写法 ...

const submitForm = () => {
  formRef.value?.validate((valid) => {
    if (valid) {
      if (form.subjectCode) {
        form.subjectCode = Number(form.subjectCode)
      }
      
      if (form.id != null) {
        updatePaper(form).then(response => {
          ElMessage.success("修改成功")
          open.value = false
          getList()
        })
      } else {
        addPaper(form).then(response => {
          ElMessage.success("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

// 生命周期钩子
onMounted(async () => {
  await getSubjectTree()
  getList()
})

// 添加输入处理函数
const handleInput = (e) => {
  if (e.key === 'Enter') {
    handleQuery()
  }
}

// 添加处理方法
const handleAdd = () => {
  reset()
  open.value = true
  title.value = "添加试卷"
}

const reset = () => {
  formRef.value?.resetFields()
  Object.assign(form, {
    id: null,
    name: null,
    subjectCode: null,
    sort: 0,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  })
}

const handleUpdate = (row) => {
  reset()
  const id = row?.id || ids.value[0]
  getPaper(id).then(response => {
    const paperData = response.data
    if (paperData.subjectCode) {
      paperData.subjectCode = Number(paperData.subjectCode)
    }
    Object.assign(form, paperData)
    open.value = true
    title.value = "修改试卷"
  })
}

const handleDelete = async (row) => {
  const paperIds = row?.id || ids.value
  await ElMessageBox.confirm('是否确认删除选中的试卷?', '警告', {
    type: 'warning'
  }).then(() => {
    return delPaper(paperIds)
  }).then(() => {
    getList()
    ElMessage.success('删除成功')
  }).catch(() => {})
}

const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

const handleQuestions = (row) => {
  router.push({
    path: '/paper/questions',
    query: {
      paperId: row.id,
      paperName: row.name
    }
  })
}

// 添加 cancel 方法
const cancel = () => {
  open.value = false
  reset()
}

// 添加导入相关方法
const handleImport = () => {
  importOpen.value = true
}

const cancelImport = () => {
  importOpen.value = false
  importForm.url = ''
}

const submitImport = () => {
  importFormRef.value?.validate((valid) => {
    if (valid) {
      // 设置加载状态
      importLoading.value = true
      
      // 保存token和siteName到localStorage
      localStorage.setItem(TOKEN_STORAGE_KEY, importForm.token)
      localStorage.setItem(SITE_NAME_STORAGE_KEY, importForm.siteName)
      
      // 构造导入参数
      const importParams = {
        websiteName: importForm.siteName,
        path: importForm.url,
        token: importForm.token
      }
      
      // 调用导入API
      importPaper(importParams).then(response => {
        ElMessage.success('导入成功')
        importOpen.value = false
        getList() // 刷新列表
        
        // 只重置url，保留token和siteName
        importForm.url = ''
      }).catch(() => {
        ElMessage.error('导入失败')
      }).finally(() => {
        // 无论成功失败都关闭加载状态
        importLoading.value = false
      })
    }
  })
}

// 添加获取科目树的方法
const getSubjectTree = () => {
  subjectTree().then(response => {
    subjectOptions.value = response.data
  })
}

// 添加科目选择处理方法
const handleSubjectChange = (value) => {
  form.subjectCode = value
}

// 修改科目树节点过滤方法
const filterSubjectNode = (search, data) => {
  console.log('过滤方法被调用:', {
    search,
    data
  })
  
  // 如果没有搜索词，显示所有节点
  if (!search) return true
  
  // 如果数据为空，返回false
  if (!data) return false
  
  // 获取节点文本
  const nodeText = data.name || ''
  
  // 执行不区分大小写的搜索
  return nodeText.toLowerCase().includes(search.toLowerCase())
}
</script>
